import {
  ClassSerializerInterceptor,
  MiddlewareConsumer,
  Module,
  NestModule,
} from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ConfigModule } from '@nestjs/config';
import config from './config';
import { ThrottlerGuard, ThrottlerModule } from '@nestjs/throttler';
import { LoggerModule } from './shared/logger/logger.module';
import { APP_FILTER, APP_GUARD, APP_INTERCEPTOR } from '@nestjs/core';
import { CustomExceptionFilter } from './shared/filter/custom-exception.filter';
import { InvokeRecordInterceptor } from './shared/interceptor/invoke-record.interceptor';
import { LoggerMiddleware } from './shared/middleware/logger.middleware';
import { SmsModule } from './shared/sms/sms.module';
import { DatabaseModule } from './shared/database/database.module';
import { UserModule } from './user/user.module';
import { AuthModule } from './shared/auth/auth.module';
import { TransactionModule } from './shared/transaction/transaction.module';
import { TenantModule } from './tenant/tenant.module';
import { ProductModule } from './product/product.module';
import { OrderModule } from './order/order.module';
import { AddressModule } from './address/address.module';
import { MemberCardModule } from './member-card/member-card.module';
import { RechargeLogModule } from './recharge-log/recharge-log.module';
import { FeedbackModule } from './feedback/feedback.module';
import { AnnouncementModule } from './announcement/announcement.module';

@Module({
  imports: [
    // 配置
    ConfigModule.forRoot({
      isGlobal: true,
      load: [...config],
    }),
    // 日志
    LoggerModule,
    // 限流
    ThrottlerModule.forRoot([
      {
        ttl: 1 * 60 * 1000, // 1 minute
        limit: 60, // how many requests
      },
    ]),
    // 数据库
    DatabaseModule,
    // 事务
    TransactionModule,
    // 短信
    SmsModule,
    // 用户
    UserModule,
    // 认证
    AuthModule,
    TenantModule,
    ProductModule,
    OrderModule,
    AddressModule,
    MemberCardModule,
    RechargeLogModule,
    FeedbackModule,
    AnnouncementModule,
  ],
  controllers: [AppController],
  providers: [
    AppService,
    AppService,
    // 应用限流守卫
    {
      provide: APP_GUARD,
      useClass: ThrottlerGuard,
    },
    // 应用类序列化拦截器
    {
      provide: APP_INTERCEPTOR,
      useClass: ClassSerializerInterceptor,
    },
    // 应用过滤器
    {
      provide: APP_FILTER,
      useClass: CustomExceptionFilter,
    },
    // 应用拦截器
    {
      provide: APP_INTERCEPTOR,
      useClass: InvokeRecordInterceptor,
    },
  ],
})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(LoggerMiddleware).forRoutes('*');
  }
}
